package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"register/models"
)

type RegisterController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *RegisterController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "get:Post")
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	cate := c.GetString("cate")
	nums, _ := c.GetInt("nums")
	img := c.GetString("img")
	we_name := c.GetString("we_name")
	tel := c.GetString("tel")
	address := c.GetString("address")
	register := models.Register{
		Name:    name,
		Num:     num,
		Cate:    cate,
		Nums:    nums,
		Img:     img,
		WeName:  we_name,
		Tel:     tel,
		Address: address,
	}
	err := models.Add(&register)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *RegisterController) Show() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "get:Post")
	id, _ := c.GetInt("id")
	var register models.Register
	err := models.DB.Model(&register).Where("id=?", id).Find(&register).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: register,
		}
		c.ServeJSON()
	}
}
func (c *RegisterController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "get:Post")
	var register []models.Register
	err := models.DB.Find(&register).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: register,
		}
		c.ServeJSON()
	}
}
